<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\Admin;
use app\model\AdminRole;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 管理员控制器
 * Class AdminController
 * @package app\controller
 */
class AdminController extends BaseController
{
    /**
     * 管理员列表
     * @return \think\response\Json
     */
    public function index()
    {
        try {
            \think\facade\Log::info('AdminController index method called');
            \think\facade\Log::info('Request URI: ' . $this->request->url());
            \think\facade\Log::info('Request params: ' . json_encode($this->request->param()));
            
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $keyword = $this->request->param('keyword', '');
            $status = $this->request->param('status', '');

            $where = [];
            if (!empty($keyword)) {
                $where[] = ['username|nickname', 'like', '%' . $keyword . '%'];
            }
            if ($status !== '') {
                $where[] = ['status', '=', $status];
            }

            $list = Admin::with(['roles'])
                ->where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);

            \think\facade\Log::info('AdminController index returning paginated list');
            return $this->paginate($list);
        } catch (\Exception $e) {
            \think\facade\Log::error('AdminController index error: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    /**
     * 管理员详情
     * @param int $id
     * @return \think\response\Json
     */
    public function read($id = null)
    {
        try {
            // 如果没有传递id参数，尝试从路由参数中获取
            if ($id === null) {
                $id = $this->request->param('id');
            }
            
            \think\facade\Log::info('AdminController read method called with id: ' . $id);
            \think\facade\Log::info('Request URL: ' . $this->request->url());
            \think\facade\Log::info('All params: ' . json_encode($this->request->param()));
            
            if (!$id) {
                \think\facade\Log::error('No id provided to read method');
                return $this->error('缺少管理员ID参数');
            }
            
            $admin = Admin::with(['roles'])->find($id);
            if (!$admin) {
                \think\facade\Log::info('Admin not found for id: ' . $id);
                return $this->error('管理员不存在');
            }

            \think\facade\Log::info('Admin found: ' . json_encode($admin->toArray()));
            return $this->success($admin);
        } catch (\Exception $e) {
            \think\facade\Log::error('AdminController read error: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    /**
     * 创建管理员
     * @return \think\response\Json
     */
    public function save()
    {
        try {
            $data = $this->request->post();
            
            // 验证数据
            $this->validate($data, [
                'username' => 'require|alphaNum|length:3,20|unique:admins',
                'password' => 'require|length:6,20',
                'nickname' => 'require|length:2,20',
                'email' => 'email',
                'phone' => 'mobile',
                'status' => 'in:0,1',
                'role_ids' => 'array'
            ], [
                'username.require' => '用户名不能为空',
                'username.alphaNum' => '用户名只能是字母和数字',
                'username.length' => '用户名长度为3-20位',
                'username.unique' => '用户名已存在',
                'password.require' => '密码不能为空',
                'password.length' => '密码长度为6-20位',
                'nickname.require' => '昵称不能为空',
                'nickname.length' => '昵称长度为2-20位',
                'email.email' => '邮箱格式不正确',
                'phone.mobile' => '手机号格式不正确',
                'status.in' => '状态值不正确',
                'role_ids.array' => '角色ID必须是数组'
            ]);

            Db::startTrans();
            try {
                // 创建管理员
                $admin = Admin::create([
                    'username' => $data['username'],
                    'password' => $data['password'],
                    'nickname' => $data['nickname'],
                    'email' => $data['email'] ?? '',
                    'phone' => $data['phone'] ?? '',
                    'avatar' => $data['avatar'] ?? '',
                    'status' => $data['status'] ?? 1
                ]);

                // 分配角色
                if (!empty($data['role_ids'])) {
                    $roleData = [];
                    foreach ($data['role_ids'] as $roleId) {
                        $roleData[] = [
                            'admin_id' => $admin->id,
                            'role_id' => $roleId,
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                    }
                    (new AdminRole())->insertAll($roleData);
                }

                Db::commit();
                return $this->success($admin, '创建成功');
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 更新管理员
     * @param int $id
     * @return \think\response\Json
     */
    public function update(int $id)
    {
        try {
            $admin = Admin::find($id);
            if (!$admin) {
                return $this->error('管理员不存在');
            }

            $data = $this->request->put();
            
            // 超级管理员状态保护
            if ($id == 1 && isset($data['status']) && $data['status'] == 0) {
                return $this->error('不能禁用超级管理员');
            }
            
            // 验证数据
            $rules = [
                'username' => 'require|alphaNum|length:3,20|unique:admins,username,' . $id,
                'nickname' => 'require|length:2,20',
                'email' => 'email',
                'phone' => 'mobile',
                'status' => 'in:0,1',
                'role_ids' => 'array'
            ];
            
            if (!empty($data['password'])) {
                $rules['password'] = 'length:6,20';
            }

            $this->validate($data, $rules, [
                'username.require' => '用户名不能为空',
                'username.alphaNum' => '用户名只能是字母和数字',
                'username.length' => '用户名长度为3-20位',
                'username.unique' => '用户名已存在',
                'password.length' => '密码长度为6-20位',
                'nickname.require' => '昵称不能为空',
                'nickname.length' => '昵称长度为2-20位',
                'email.email' => '邮箱格式不正确',
                'phone.mobile' => '手机号格式不正确',
                'status.in' => '状态值不正确',
                'role_ids.array' => '角色ID必须是数组'
            ]);

            Db::startTrans();
            try {
                // 更新管理员信息
                $updateData = [
                    'username' => $data['username'],
                    'nickname' => $data['nickname'],
                    'email' => $data['email'] ?? '',
                    'phone' => $data['phone'] ?? '',
                    'avatar' => $data['avatar'] ?? '',
                    'status' => $data['status'] ?? 1
                ];

                if (!empty($data['password'])) {
                    $updateData['password'] = $data['password'];
                }

                $admin->save($updateData);

                // 更新角色
                AdminRole::where('admin_id', $id)->delete();
                if (!empty($data['role_ids'])) {
                    $roleData = [];
                    foreach ($data['role_ids'] as $roleId) {
                        $roleData[] = [
                            'admin_id' => $id,
                            'role_id' => $roleId,
                            'created_at' => date('Y-m-d H:i:s')
                        ];
                    }
                    (new AdminRole())->insertAll($roleData);
                }

                Db::commit();
                return $this->success($admin, '更新成功');
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 删除管理员
     * @param int $id
     * @return \think\response\Json
     */
    public function delete(int $id)
    {
        try {
            if ($id == 1) {
                return $this->error('不能删除超级管理员');
            }

            $admin = Admin::find($id);
            if (!$admin) {
                return $this->error('管理员不存在');
            }

            Db::startTrans();
            try {
                // 删除角色关联
                AdminRole::where('admin_id', $id)->delete();
                // 删除管理员
                $admin->delete();

                Db::commit();
                return $this->success([], '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 批量删除管理员
     * @return \think\response\Json
     */
    public function batchDelete()
    {
        try {
            $ids = $this->request->post('ids', []);
            if (empty($ids) || !is_array($ids)) {
                return $this->error('请选择要删除的管理员');
            }

            // 不能删除超级管理员
            if (in_array(1, $ids)) {
                return $this->error('不能删除超级管理员');
            }

            Db::startTrans();
            try {
                // 删除角色关联
                AdminRole::whereIn('admin_id', $ids)->delete();
                // 删除管理员
                Admin::whereIn('id', $ids)->delete();

                Db::commit();
                return $this->success([], '批量删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 修改状态
     * @param int $id
     * @return \think\response\Json
     */
    public function changeStatus(int $id)
    {
        try {
            if ($id == 1) {
                return $this->error('不能修改超级管理员状态');
            }

            $admin = Admin::find($id);
            if (!$admin) {
                return $this->error('管理员不存在');
            }

            $status = $this->request->post('status');
            if (!in_array($status, [0, 1])) {
                return $this->error('状态值不正确');
            }

            $admin->status = $status;
            $admin->save();

            return $this->success([], '状态修改成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}